#include <webx/export.h>

static void CoverConfigFile()
{
	if (RedisConnect::CanUse())
	{
		sp<RedisConnect> redis = RedisConnect::Instance();

		if (redis)
		{
			YAMLoader::Instance()->set("redis.password", redis->getPassword());
			YAMLoader::Instance()->set("redis.host", redis->getHost());
			YAMLoader::Instance()->set("redis.port", redis->getPort());
		}
	}
}

class ReloadWorkItem : public WorkItem
{
public:
	void run()
	{
		CoverConfigFile();
	}
};

static void ReloadSystemConfig()
{
	stdx::async(newsp<ReloadWorkItem>());

	Sleep(100);
}

EXTERN_DLL_FUNC int HttpPluginInit(HttpServer* app, const char* path)
{
	auto loadPlugin = [app](string path){
		CHECK_FALSE_RETURN(path::type(path) == ePATH);

		vector<string> vec;

		CHECK_FALSE_RETURN(stdx::FindFile(vec, path, "*.so") > 0);

		if (!stdx::endwith(path, "/")) path += "/";

		for (auto& item : vec) item = item.substr(path.length());

		std::sort(vec.begin(), vec.end(), [](const string& a, const string& b){
			if (a == "RouteModule.so") return false;
			if (b == "RouteModule.so") return true;
			return a < b;
		});

		for (auto& item : vec)
		{
			if (item == "InitSystem.so") continue;

			app->loadPlugin(path + item);
		}

		return true;
	};

	string localplugpath = app->getPath() + "etc/plugin/bin";
	string globalplugpath = stdx::translate("$CPPWEB_INSTALL_HOME/webapp/etc/plugin/bin");

	if (localplugpath == globalplugpath)
	{
		loadPlugin(localplugpath);
	}
	else
	{
		loadPlugin(globalplugpath);
		loadPlugin(localplugpath);
	}

	Process::SetObject("HTTP_RELOAD_SYSTEM_CONFIG_FUNC", (void*)ReloadSystemConfig);

	string home = proc::env("CPPWEB_PRODUCT_HOME");

	if (home.length() > 0)
	{
		Process::RegisterLibraryPath(home + "/lib/openssl/lib");
		Process::RegisterLibraryPath(home + "/lib/mysql/lib");
	}

	CoverConfigFile();

	return XG_OK;
}